package com.xht.service.impl;

import cn.hutool.json.JSONUtil;
import com.xht.constants.SystemConstants;
import com.xht.domain.ResponseResult;
import com.xht.domain.entity.LoginUser;
import com.xht.domain.entity.User;
import com.xht.service.BlogLoginService;
import com.xht.utils.BeanCopyUtils;
import com.xht.utils.JwtUtil;
import com.xht.vo.BlogUserLoginVo;
import com.xht.vo.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Objects;

import static cn.hutool.core.lang.Console.log;

@Slf4j
@Service
public class BlogLoginServiceImpl implements BlogLoginService {


    /**
     * 在springMVC默认容器中是没有AuthenticationManager，需要配置
     * 定义配置类
     */
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public ResponseResult login(User user) {

        /**
         * 没认证情况下第一个参数传用户名，第二个参数传用户密码
         */
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());

        /**
         * 其中执行下面方法时候，就会自动去调用UserDetailsService类中的方法
         * 然后去验证 账户密码的正确性，
         * 需要自定义UserDetailsService的实现类,
         */
        //实现用户的登录认证
        Authentication authenticate =
                //authenticate()方法会调用UserDetailsService的实现类中的loadUserByUsername方法
                // ,从中去验证用户信息是否输入正确
                authenticationManager.authenticate(authenticationToken);

        //判断是否认证通过
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("用户密码错误拉!!!");
        }

        //获取userId 生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        Long userId = loginUser.getUser().getId();
        //将userId进行加密,利用jwt
        // ,但是jwt需要传入一个String类型
        String jwt = JwtUtil.createJWT(userId.toString());
        log(jwt);

//        //把用户信息存入redis
        stringRedisTemplate.opsForValue().set(SystemConstants.BLOG_LOGIN + userId, JSONUtil.toJsonStr(loginUser));

        //把token和userInfo封装 并返回
        UserInfo userInfo = BeanCopyUtils.copyBean(loginUser.getUser(), UserInfo.class);
        BlogUserLoginVo blogUserLoginVo = new BlogUserLoginVo(jwt, userInfo);
        return ResponseResult.okResult(blogUserLoginVo);
    }

    @Override
    public ResponseResult logout() {
        //在响应头中获取Token
        Authentication authentication =
                SecurityContextHolder.getContext().getAuthentication();


        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
//        User test = loginUser.getUser();
//        // 检查当前用户是否是匿名用户
//        if (Objects.isNull(test) || authentication instanceof AnonymousAuthenticationToken) {
//            log("我访问到这里了!!!!!!!");
//            // 如果是匿名用户，直接返回成功
//           // return ResponseResult.okResult();
//        }


        //获取用户id
        Long userId = loginUser.getUser().getId();

        //将redis缓存 删除
        stringRedisTemplate.delete(SystemConstants.BLOG_LOGIN + userId);

        return ResponseResult.okResult();
    }
}
